/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        queue<Node*>q;
        if(root)q.push(root);
        while(q.size())
        {
            int sz=q.size();
            auto node=q.front();
            q.pop();
            if(node->left)q.push(node->left);
            if(node->right)q.push(node->right);
            for(int i=sz-1;i>0;i--)
            {
                auto tmp=q.front();
                if(tmp->left)q.push(tmp->left);
                if(tmp->right)q.push(tmp->right);
                q.pop();
                node->next=tmp;
                node=tmp;
            }
            node->next=nullptr;
        }
        return root;
    }
};
